package com.cssy.xxkj.logic.web;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.xxkj.basic.entity.BasicStorageInfoTestDO;
import com.cssy.xxkj.basic.service.IBasicCompanyTestService;
import com.cssy.xxkj.basic.service.IBasicUtilService;
import com.cssy.xxkj.logic.contants.BillStatusUtil;
import com.cssy.xxkj.logic.entity.LogicPurchaseDO;
import com.cssy.xxkj.logic.entity.LogicPurchaseReturnDO;
import com.cssy.xxkj.logic.entity.LogicPurchaseReturnItemDO;
import com.cssy.xxkj.logic.entity.LogicPurchaseWareDO;
import com.cssy.xxkj.logic.entity.LogicPurchaseWareItemDO;
import com.cssy.xxkj.logic.service.ILogicPurchaseReturnItemService;
import com.cssy.xxkj.logic.service.ILogicPurchaseReturnService;
import com.cssy.xxkj.logic.service.ILogicPurchaseService;
import com.cssy.xxkj.logic.service.ILogicPurchaseWareItemService;
import com.cssy.xxkj.logic.service.ILogicPurchaseWareService;
import com.cssy.xxkj.logic.service.ILogicUtilService;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.json.OutJsonGrid;

@Controller
@RequestMapping("/logic/purchasereturn")
public class PurchaseReturnController extends BaseController<LogicPurchaseReturnDO> {

	private static final String MANAGER = "/xxkj/logic/purchasereturn/PurchaseReturnManager";
	private static final String EIDT = "/xxkj/logic/purchasereturn/PurchaseReturnOperation";
	
	@Resource(name = "basicUtilService")
	IBasicUtilService basicUtilService;
	
	@Resource(name = "logicUtilService")
	ILogicUtilService logicUtilService;
	
	@Resource(name = "logicPurchaseWareService")
	ILogicPurchaseWareService logicPurchaseWareService;
	
	@Resource(name = "logicPurchaseWareItemService")
	ILogicPurchaseWareItemService logicPurchaseWareItemService;
	
	@Resource(name = "logicPurchaseReturnService")
	ILogicPurchaseReturnService logicPurchaseReturnService;
	
	@Resource(name = "logicPurchaseReturnItemService")
	ILogicPurchaseReturnItemService logicPurchaseReturnItemService;	
	
	@Resource(name="basicCompanyTestService")
	IBasicCompanyTestService basicCompanyTestService;
	
	@Resource(name = "logicPurchaseService")
	ILogicPurchaseService logicPurchaseService;
	
	
	
	@Override
	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		hander.getWheres(scs);
		scs.setRemovedProperty("removed");
		List<BasicStorageInfoTestDO> list = basicUtilService.resultStorage(scs);
		model.addAttribute("wh",list);
		return MANAGER;
	}

	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		hander.getWheres(scs);
		if(StringUtils.isBlank(scs.getOrderBy())){
			scs.setOrderBy(" zd011BackDate desc, zd003Code desc ");
		}
		SearchResult result = logicPurchaseReturnService.findListByExample(scs);
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);
		
	}

	@Override
	public String operationForm(HttpServletRequest request, @PathVariable String id,
			@PathVariable String flag, Model model) throws Exception {
		if (OperationFlag.ADD.equals(flag)) {
			model.addAttribute("flag", "ADD");
		} else {
			
			LogicPurchaseReturnDO pcsr = logicPurchaseReturnService.findListById(id);
			model.addAttribute("pcsr", pcsr);
		}
		//查询采购入库单
		SearchConditions pcsScs = new SearchConditions();
		pcsScs.setRemovedProperty(null);
		List<LogicPurchaseDO> pcsList = logicUtilService.resultPurchase(pcsScs);
		model.addAttribute("pcsList", pcsList);
		//查询仓库
		SearchConditions whScs = new SearchConditions();
		whScs.setRemovedProperty(null);
		List<BasicStorageInfoTestDO> whList = basicUtilService.resultStorage(whScs);
		model.addAttribute("whList", whList);
		return EIDT;
	}

	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicPurchaseReturnDO curAP, BindingResult result, Model model)
			throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try{
			String itemdata = request.getParameter("itemdata");
			if(StringUtils.isBlank(itemdata)){
				bodyMap.isFail();
				bodyMap.configWebInfor("产品列表不能为空！");
				return bodyMap.modelMap;
			}
			/*if(StringUtils.isBlank(curAP.getZd022PiCode())){
				bodyMap.isFail();
				bodyMap.configWebInfor("PI编号不能为空！");
				return bodyMap.modelMap;
			}*/
			logicPurchaseReturnService.purchaseReturnSave(curAP, request);
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
		}catch(Exception e){
			e.printStackTrace();
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()+ e.getMessage());
		}
		return bodyMap.modelMap;
	}

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String ids = request.getParameter("ids");
			String[] fields=ids.split(",");
			for(String field : fields){
				if(StringUtils.isBlank(field)){
					continue;
				}else{
					logicPurchaseReturnService.deleteBizRemoved(field);
				}
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}
	
	/**
	 * 查询采购退货单的行记录
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/gridItems")
	public void gridItems(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String pcsrId = request.getParameter("pcsrId");
		if(StringUtils.isNotBlank(pcsrId)){
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("pcsrId", pcsrId);
			List<LogicPurchaseReturnItemDO> pcsrmList = logicPurchaseReturnItemService.findListByMap(paramMap);
			OutJsonGrid out = new OutJsonGrid(pcsrmList);
			out.printJSon(response);
		}
	}

	/**
	 * 根据采购订单查询采购入库单
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/pcswList")
	@ResponseBody
	public List<LogicPurchaseWareDO> pcswList(HttpServletRequest request, HttpServletResponse response)throws Exception{
		String pcsId = request.getParameter("pcsId");
		List<LogicPurchaseWareDO> pcswList = new ArrayList<LogicPurchaseWareDO>();
		if(StringUtils.isNotBlank(pcsId)){
			SearchConditions pcswScs = new SearchConditions();
			pcswScs.setRemovedProperty(null);
			pcswScs.addCondition("zd001PcsId", pcsId, SearchCondition.OP_EQUAL);
			try{
				List<LogicPurchaseWareDO> _pcswList = logicUtilService.resultPurchaseWare(pcswScs);
				pcswList.addAll(_pcswList);
			}catch(Exception e){
				throw new RuntimeException();
			}
		}
		return pcswList;
	}
	
	/**
	 * 根据采购入库单ID查询采购入库单
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/pcsm")
	@ResponseBody
	public LogicPurchaseWareDO pcsm(HttpServletRequest request, HttpServletResponse response)throws Exception{
		String pcsmId = request.getParameter("pcsmId");
		LogicPurchaseWareDO pcsm = null;
		if(StringUtils.isNotBlank(pcsmId)){
			try{
				pcsm = logicPurchaseWareService.findListById(pcsmId);
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		return pcsm;
	}
	
	/**
	 * 根据采购入库单ID查询采购入库单item集合
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/pcsmItemList")
	
	public void pcsmItemList(HttpServletRequest request, HttpServletResponse response)throws Exception{
		String pcsmId = request.getParameter("pcsmId");
		if(StringUtils.isNotBlank(pcsmId)){
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("pcswId", pcsmId);
			List<LogicPurchaseWareItemDO> pcswItemList = logicPurchaseWareItemService.findListByMap(paramMap);
			if(pcswItemList==null){
				pcswItemList = new ArrayList<LogicPurchaseWareItemDO>();
			}
			//查询已审核过的采购退货单
			Map<String, BigDecimal> pcsrHsMap = new HashMap<String, BigDecimal>();
			Map<String, Object> pcsrMap = new HashMap<String, Object>();
			pcsrMap.put("pcsmId", pcsmId);
			pcsrMap.put("zdStatus", BillStatusUtil.PCSR_BILL_STATUS_FOUR);
		    List<LogicPurchaseReturnItemDO> pcsrmExList = logicPurchaseReturnItemService.findListByMap(paramMap);
		    if(pcsrmExList!=null && !pcsrmExList.isEmpty() && pcsrmExList.size()>0){
		    	for(LogicPurchaseReturnItemDO pcsrmEx : pcsrmExList){
		    		if(pcsrmEx==null || StringUtils.isBlank(pcsrmEx.getId())){
		    			continue;
		    		}
		    		BigDecimal rnQuantity = pcsrmEx.getZd020BackQuantity()==null?BigDecimal.ZERO:pcsrmEx.getZd020BackQuantity();
		    		String keyStr = pcsrmEx.getZd003MaterId()+"_"+pcsrmEx.getZd008MaterModel()+"_"
		    				+pcsrmEx.getZd012MaterSize()+"_"+pcsrmEx.getZd010MaterColor()+"_"
		    				+pcsrmEx.getZd011MaterQuality();
		    		if(pcsrHsMap.get(keyStr)==null){
		    			pcsrHsMap.put(keyStr, rnQuantity);
		    		}else{
		    			pcsrHsMap.put(keyStr, rnQuantity.add(pcsrHsMap.get(keyStr)));
		    		}
		    	}
		    }
		    //组装退货单
			List<LogicPurchaseReturnItemDO> pcsrmList = new ArrayList<LogicPurchaseReturnItemDO>();
			for(LogicPurchaseWareItemDO pcswItem : pcswItemList){
				if(pcswItem==null){
					continue;
				}
				String keyStr = pcswItem.getZd003MaterId()+"_"+pcswItem.getZd007Model()+"_"
						+pcswItem.getZd011Size()+"_"+pcswItem.getZd009Color()+"_"
						+pcswItem.getZd010Quality();
				LogicPurchaseReturnItemDO pcsrm = new LogicPurchaseReturnItemDO();
				pcsrm.setZd003MaterId(pcswItem.getZd003MaterId());
				pcsrm.setZd004MaterCode(pcswItem.getZd004Code());
				pcsrm.setZd005MaterName(pcswItem.getZd005Name());
				pcsrm.setZd006MaterType(pcswItem.getZd005Type());
				pcsrm.setZd006MaterType(pcswItem.getZd006Spec());
				pcsrm.setZd008MaterModel(pcswItem.getZd007Model());
				pcsrm.setZd009MaterBrand(pcswItem.getZd008Brand());
				pcsrm.setZd010MaterColor(pcswItem.getZd009Color());
				pcsrm.setZd011MaterQuality(pcswItem.getZd010Quality());
				pcsrm.setZd012MaterSize(pcswItem.getZd011Size());
				pcsrm.setZd013TaxPrice(pcswItem.getZd017TaxPrice());
				pcsrm.setZd014Price(pcswItem.getZd016Price());
				pcsrm.setZd016Unit(pcswItem.getZd012Unit());
				//订单数量
				pcsrm.setZd022Quantity(pcswItem.getZd014Quatity());
				//退货时的已入库数量
				//BigDecimal inQuantity = pcswItem.getZd022InQuantity()==null?BigDecimal.ZERO:pcswItem.getZd022InQuantity();
				BigDecimal theQuantity = pcswItem.getZd018HsQuantity()==null?BigDecimal.ZERO:pcswItem.getZd018HsQuantity();
				pcsrm.setZd018InQuantiy(theQuantity);
				//已退货数量
				if(pcsrHsMap.get(keyStr)==null){
					pcsrm.setZd024HsBackQuantity(BigDecimal.ZERO);
				}else{
					pcsrm.setZd024HsBackQuantity(pcsrHsMap.get(keyStr));
				}
				pcsrmList.add(pcsrm);
			}
			OutJsonGrid out = new OutJsonGrid(pcsrmList);
			out.printJSon(response);
		}
	}
	
	
}
